#include <semaphore.h>
#include <stdio.h>
#include <pthread.h>

#define M 10
#define N 20

sem_t sfork[5];

void *philosopher1 (void *p){//方案1
   int id =(int)p; 
   while(1){
        printf("Thinking...\n");
        if(id%2==0){
             sem_wait(&sfork[id]);
             sem_wait(&sfork[(id+1)%5]);
       }else{
              sem_wait(&sfork[(id+1)%5]);
              sem_wait(&sfork[id]);
       }
        printf("Eating...\n");
        sem_post(&sfork[id]);
        sem_post(&sfork[(id+1)%5]);
    }  return NULL;
}

void *philosopher2 (void *p){//方案2
   int id =(int)p; 
   while(1){
        printf("Thinking...\n");
        if(id==4){
             sem_wait(&sfork[0]);
             sem_wait(&sfork[4]);
       }else{
              sem_wait(&sfork[id]);
              sem_wait(&sfork[id+1]);
       }
        printf("Eating...\n");
        sem_post(&sfork[id]);
        sem_post(&sfork[(id+1)%5]);
    }  return NULL;
}

int main(void){
    for(int i=0; i<5; i++) 
        sem_init(&sfork[i], 0, 1); 
    pthread_t tid[5];
    for(int i=0; i<5; i++) 
        pthread_create(&tid[i], NULL, philosopher1 , (void*) i); //方案1
        //pthread_create(&tid[i], NULL, philosopher2 , (void*) i); //方案2
    for(int i=0; i<M; i++) 
        sem_destroy(&sfork[i]); 
    pthread_join(tid[0], NULL);
}